package com.zrrd.jt_admin.common.intercept;

import com.alibaba.fastjson.JSON;
import com.zrrd.jt_admin.common.exception.TokenException;
import com.zrrd.jt_admin.common.response.ResponseResult;
import com.zrrd.jt_admin.common.utils.ContextHolder;
import com.zrrd.jt_admin.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author WanJl
 * @version 1.0
 * @title TokenInterceptor
 * @description
 * @create 2024/7/2
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 前端发送过来的请求头中的属性名
     */
    private static final String HEADER_NAME = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            //从请求头中读取token
            String token = request.getHeader(HEADER_NAME);

            if (StringUtils.isBlank(token)) {
                log.info("没有token，token为空");
                throw new TokenException("没有token，token为空");
            }

            //解析token
            Map<String, Object> map = JwtUtils.analysisToken(token);

            //获取id
            Long id = Long.valueOf(map.get("id").toString());
            //在本地线程中添加id
            ContextHolder.setId(id);
            return true;
        }catch (TokenException e){
            log.info(e.getMessage());
            response.setContentType("application/json;charset=utf-8");
            ResponseResult responseResult = ResponseResult.defaultResponse(false, e.getMessage(), e.getMessage());
            String jsonString = JSON.toJSONString(responseResult);
            response.getWriter().print(jsonString);
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //在本地线程中删除id
        ContextHolder.shutdown();
    }
}
